package servlet;

import java.io.IOException;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import entity.User;
import session.UserDao;

/**
 * Kontroler koji služi za menjanje profila korisnika. Koristi se
 * sa strane administracije.
 *  
 * @author en_e
 *
 */
public class UserEditAdmin extends HttpServlet {
	private static final long serialVersionUID = 531395085730230215L;
	
	@EJB
	protected UserDao userDao ;
	 
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try{
			User admin;
			/*provera da li je korisnik prijavljen i da li je administrator
			 * 
			 */
			if((admin = (User)request.getSession().getAttribute("user"))==null ||
					admin.getType()!='A'){
				response.sendRedirect(response.encodeURL("./login.jsp"));
				return;
			}
			Integer userId = null;
			if(request.getParameter("idUsr")!=null && !request.getParameter("idUsr").equals("")){
				userId = Integer.parseInt(request.getParameter("idUsr"));
			}else{
				response.sendRedirect(response.encodeURL("./ListUsers"));
			}

			String firstName, lastName, phone;			
			Character type = 'K';
			User usr = userDao.findById(userId);
			
			if((firstName =  request.getParameter("firstName"))!= null && !firstName.trim().equals(""))
				usr.setFirstName(firstName);
					
			if((lastName =  request.getParameter("lastName"))!= null && !lastName.trim().equals(""))
				usr.setLastName(lastName);	
							
			if((phone =  request.getParameter("phone"))!= null && !phone.trim().equals(""))
				usr.setPhone(phone);
			
			if((phone =  request.getParameter("phone"))!= null && !phone.trim().equals(""))
				usr.setPhone(phone);
			
			if (request.getParameter("admin")!=null && !request.getParameter("admin").equals("")){
				if(request.getParameter("admin").equals("true"))
					type = 'A';
			}
			if (request.getParameter("delPic")!=null && !request.getParameter("delPic").equals("")){
				if(request.getParameter("delPic").equals("true"))
					usr.setAvatar("default.gif");
			}
			usr.setType(type);
			
			userDao.merge(usr);
			response.sendRedirect(response.encodeURL("./ListUsers"));
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}
